<template>
  <div class="salary-calculation">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>工资计算</h2>
    </div>

    <!-- 计算条件 -->
    <div class="calculation-form">
      <el-card header="工资计算条件" class="form-card">
        <el-form :model="calculationForm" inline>
          <el-form-item label="员工">
            <el-select
              v-model="calculationForm.employeeId"
              placeholder="请选择员工"
              filterable
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="employee in employeeList"
                :key="employee.id"
                :label="employee.name"
                :value="employee.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="计算月份">
            <el-date-picker
              v-model="calculationForm.month"
              type="month"
              placeholder="请选择月份"
              format="YYYY-MM"
              value-format="YYYY-MM"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleCalculate" :loading="calculating">
              计算工资
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 工资计算结果 -->
    <div v-if="salaryResult" class="salary-result">
      <el-card header="工资计算结果" class="result-card">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="result-item">
              <div class="result-label">员工姓名</div>
              <div class="result-value">{{ salaryResult.employeeName }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="result-item">
              <div class="result-label">员工类型</div>
              <div class="result-value">
                <el-tag :type="getEmployeeTypeTagType(salaryResult.employeeType)">
                  {{ getEmployeeTypeText(salaryResult.employeeType) }}
                </el-tag>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="result-item">
              <div class="result-label">计算月份</div>
              <div class="result-value">{{ salaryResult.month }}</div>
            </div>
          </el-col>
        </el-row>

        <el-divider />

        <el-row :gutter="20">
          <el-col :span="6">
            <div class="result-item highlight">
              <div class="result-label">基本工资</div>
              <div class="result-value">¥{{ salaryResult.baseSalary }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="result-item">
              <div class="result-label">工作天数</div>
              <div class="result-value">{{ salaryResult.workDays }}天</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="result-item">
              <div class="result-label">工作小时</div>
              <div class="result-value">{{ salaryResult.workHours }}小时</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="result-item">
              <div class="result-label">加班小时</div>
              <div class="result-value">{{ salaryResult.overtimeHours }}小时</div>
            </div>
          </el-col>
        </el-row>

        <el-divider />

        <el-row :gutter="20">
          <el-col :span="6">
            <div class="result-item">
              <div class="result-label">加班费</div>
              <div class="result-value">¥{{ salaryResult.overtimePay }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="result-item">
              <div class="result-label">绩效奖金</div>
              <div class="result-value">¥{{ salaryResult.performanceBonus }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="result-item">
              <div class="result-label">其他补贴</div>
              <div class="result-value">¥{{ salaryResult.allowances }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="result-item">
              <div class="result-label">扣除项</div>
              <div class="result-value text-danger">-¥{{ salaryResult.deductions }}</div>
            </div>
          </el-col>
        </el-row>

        <el-divider />

        <el-row>
          <el-col :span="24">
            <div class="result-item total">
              <div class="result-label">应发工资总额</div>
              <div class="result-value total-amount">¥{{ salaryResult.totalSalary }}</div>
            </div>
          </el-col>
        </el-row>

        <div class="result-actions">
          <el-button type="success" @click="handleSaveSalary">保存工资记录</el-button>
          <el-button type="primary" @click="handlePrintSalary">打印工资单</el-button>
        </div>
      </el-card>
    </div>

    <!-- 工资记录列表 -->
    <div class="salary-records">
      <el-card header="工资记录" class="records-card">
        <div class="records-toolbar">
          <el-form :model="recordsSearchForm" inline>
            <el-form-item label="员工">
              <el-select
                v-model="recordsSearchForm.employeeId"
                placeholder="请选择员工"
                filterable
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="employee in employeeList"
                  :key="employee.id"
                  :label="employee.name"
                  :value="employee.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="月份范围">
              <el-date-picker
                v-model="recordsSearchForm.dateRange"
                type="monthrange"
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                format="YYYY-MM"
                value-format="YYYY-MM"
                style="width: 250px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearchRecords">查询</el-button>
              <el-button @click="handleResetRecords">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          v-loading="recordsLoading"
          :data="salaryRecords"
          stripe
          border
        >
          <el-table-column prop="employeeName" label="员工姓名" width="120" />
          <el-table-column prop="employeeType" label="员工类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getEmployeeTypeTagType(row.employeeType)">
                {{ getEmployeeTypeText(row.employeeType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="month" label="月份" width="100" />
          <el-table-column prop="baseSalary" label="基本工资" width="100">
            <template #default="{ row }">
              ¥{{ row.baseSalary }}
            </template>
          </el-table-column>
          <el-table-column prop="workDays" label="工作天数" width="100" />
          <el-table-column prop="workHours" label="工作小时" width="100" />
          <el-table-column prop="overtimePay" label="加班费" width="100">
            <template #default="{ row }">
              ¥{{ row.overtimePay }}
            </template>
          </el-table-column>
          <el-table-column prop="totalSalary" label="总工资" width="120">
            <template #default="{ row }">
              <span class="total-salary">¥{{ row.totalSalary }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="150">
            <template #default="{ row }">
              {{ formatDateTime(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleViewDetail(row)">
                详情
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteRecord(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="recordsPagination.page"
            v-model:page-size="recordsPagination.size"
            :total="recordsPagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleRecordsSizeChange"
            @current-change="handleRecordsCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  calculateEmployeeSalary,
  getSalaryList,
  deleteSalary
} from '@/api/salary'
import { getActiveEmployees } from '@/api/employee'

// 响应式数据
const calculating = ref(false)
const recordsLoading = ref(false)
const employeeList = ref([])
const salaryResult = ref(null)
const salaryRecords = ref([])

// 计算表单
const calculationForm = reactive({
  employeeId: null,
  month: ''
})

// 记录搜索表单
const recordsSearchForm = reactive({
  employeeId: null,
  dateRange: []
})

// 记录分页信息
const recordsPagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 获取员工列表
const fetchEmployeeList = async () => {
  try {
    const response = await getActiveEmployees()
    employeeList.value = response.data || []
  } catch (error) {
    ElMessage.error('获取员工列表失败')
  }
}

// 计算工资
const handleCalculate = async () => {
  if (!calculationForm.employeeId) {
    ElMessage.warning('请选择员工')
    return
  }
  if (!calculationForm.month) {
    ElMessage.warning('请选择计算月份')
    return
  }

  calculating.value = true
  try {
    const response = await calculateEmployeeSalary(
      calculationForm.employeeId,
      calculationForm.month
    )
    salaryResult.value = response.data
    ElMessage.success('工资计算完成')
  } catch (error) {
    ElMessage.error('工资计算失败')
  } finally {
    calculating.value = false
  }
}

// 重置计算表单
const handleReset = () => {
  Object.assign(calculationForm, {
    employeeId: null,
    month: ''
  })
  salaryResult.value = null
}

// 保存工资记录
const handleSaveSalary = async () => {
  if (!salaryResult.value) {
    ElMessage.warning('请先计算工资')
    return
  }

  try {
    // 这里应该调用保存工资记录的API
    ElMessage.success('工资记录保存成功')
    fetchSalaryRecords()
  } catch (error) {
    ElMessage.error('保存工资记录失败')
  }
}

// 打印工资单
const handlePrintSalary = () => {
  if (!salaryResult.value) {
    ElMessage.warning('请先计算工资')
    return
  }
  
  // 这里实现打印功能
  window.print()
}

// 获取工资记录列表
const fetchSalaryRecords = async () => {
  recordsLoading.value = true
  try {
    const params = {
      page: recordsPagination.page - 1,
      size: recordsPagination.size
    }
    
    if (recordsSearchForm.employeeId) {
      params.employeeId = recordsSearchForm.employeeId
    }
    
    if (recordsSearchForm.dateRange && recordsSearchForm.dateRange.length === 2) {
      params.startMonth = recordsSearchForm.dateRange[0]
      params.endMonth = recordsSearchForm.dateRange[1]
    }

    const response = await getSalaryList(params)
    salaryRecords.value = response.data.content || []
    recordsPagination.total = response.data.totalElements || 0
  } catch (error) {
    ElMessage.error('获取工资记录失败')
  } finally {
    recordsLoading.value = false
  }
}

// 搜索记录
const handleSearchRecords = () => {
  recordsPagination.page = 1
  fetchSalaryRecords()
}

// 重置记录搜索
const handleResetRecords = () => {
  Object.assign(recordsSearchForm, {
    employeeId: null,
    dateRange: []
  })
  recordsPagination.page = 1
  fetchSalaryRecords()
}

// 查看详情
const handleViewDetail = (row) => {
  ElMessage.info('查看工资详情功能待实现')
}

// 删除记录
const handleDeleteRecord = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${row.employeeName} 在 ${row.month} 的工资记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteSalary(row.id)
    ElMessage.success('删除成功')
    fetchSalaryRecords()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 记录分页大小变化
const handleRecordsSizeChange = (size) => {
  recordsPagination.size = size
  recordsPagination.page = 1
  fetchSalaryRecords()
}

// 记录当前页变化
const handleRecordsCurrentChange = (page) => {
  recordsPagination.page = page
  fetchSalaryRecords()
}

// 获取员工类型标签类型
const getEmployeeTypeTagType = (type) => {
  const typeMap = {
    FULL_TIME: 'success',
    PART_TIME: 'warning',
    TEMPORARY: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取员工类型文本
const getEmployeeTypeText = (type) => {
  const typeMap = {
    FULL_TIME: '全职',
    PART_TIME: '兼职',
    TEMPORARY: '临时工'
  }
  return typeMap[type] || type
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchEmployeeList()
  fetchSalaryRecords()
})
</script>

<style scoped>
.salary-calculation {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.calculation-form {
  margin-bottom: 20px;
}

.form-card,
.result-card,
.records-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-card :deep(.el-card__header),
.result-card :deep(.el-card__header),
.records-card :deep(.el-card__header) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.salary-result {
  margin-bottom: 20px;
}

.result-item {
  text-align: center;
  padding: 15px;
  border-radius: 4px;
  background-color: #fafafa;
  margin-bottom: 10px;
}

.result-item.highlight {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.result-item.total {
  background-color: #f6ffed;
  border: 2px solid #b7eb8f;
}

.result-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.result-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.total-amount {
  font-size: 24px;
  color: #52c41a;
}

.text-danger {
  color: #ff4d4f;
}

.result-actions {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.records-toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.total-salary {
  font-weight: 600;
  color: #52c41a;
}

.el-table {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>